package com.bf.xpdd.web.controller.activity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bf.xpdd.domain.ActivityBean;
import com.bf.xpdd.domain.ActivityGlobal;
import com.bf.xpdd.domain.ActivityItemBean;
import com.bf.xpdd.domain.ActivityRecordBean;
import com.bf.xpdd.domain.ActivitySettingBean;
import com.bf.xpdd.domain.GridPage;
import com.bf.xpdd.domain.JSONResponse;
import com.bf.xpdd.domain.SiteItem;
import com.bf.xpdd.domain.SiteSeller;
import com.bf.xpdd.domain.TaobaoItemResult;
import com.bf.xpdd.exception.BaseException;
import com.bf.xpdd.service.AccountService;
import com.bf.xpdd.service.ActivityGlobalService;
import com.bf.xpdd.service.ActivityItemService;
import com.bf.xpdd.service.ActivityRecordService;
import com.bf.xpdd.service.ActivityService;
import com.bf.xpdd.service.ActivitySettingService;
import com.bf.xpdd.service.TaobaoService;
import com.bf.xpdd.util.ActivityUtility;
import com.bf.xpdd.util.Constant;
import com.bf.xpdd.util.JSONTranslator;
import com.taobao.api.domain.Item;

/**
 * Activity controller
 * 
 * @author Fantastic
 * @version 1.0.0 2011-05-31
 * @since 1.0.0
 */
@Controller
@RequestMapping(value = "/activity")
public class ActivityController
{
	/** logger */
	private static final Logger logger = Logger.getLogger(ActivityController.class);

	/** service */
	@Autowired
	private TaobaoService taobaoService;

	/** account service */
	// @Autowired
	// private AccountService accountService;

	/**
	 * 活动管理服务
	 */
	@Autowired
	private ActivityService activityService;

	/**
	 * 活动模板管理服务
	 */
	@Autowired
	private ActivitySettingService activitySettingService;

	/**
	 * 活动商品服务
	 */
	@Autowired
	private ActivityItemService activityItemService;

	/**
	 * 活动成交记录服务
	 */
	@Autowired
	private ActivityRecordService activityRecordService;

	/**
	 * 全局属性服务
	 */
	@Autowired
	private ActivityGlobalService activityGlobalService;
	
	/**
	 * 全局属性服务
	 */
	@Autowired
	private AccountService accountService;

	/**
	 * 活动管理的默认页面
	 * 
	 * @return pagepath
	 * @throws IOException
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String showDefault(HttpServletRequest request, HttpServletResponse response)
			throws IOException
	{
		// 从session中获取User
		SiteSeller seller = ActivityUtility.getSellerFromSession(request.getSession());
		// 如果global存在,展示,不存在,创建
		ActivityGlobal global = this.activityGlobalService.queryGlobalByNick(seller.getNick());
		// 这里判断时间,当前时间<开始时间,当前时间>结束时间 修改
		int rightCode = ActivityUtility.getRightCode(global.getBeginTime(), global.getEndTime());
		request.setAttribute("rightCode", rightCode);
		request.setAttribute("global", global);
		request.getSession().setAttribute("global", global);
		return "activity/act_global";
	}

	/**
	 * created activities
	 * 
	 * @return page
	 * @throws IOException
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/global")
	public String showBase(HttpServletRequest request, HttpServletResponse response)
			throws IOException
	{
		// 从session中获取User
		SiteSeller seller = ActivityUtility.getSellerFromSession(request.getSession());
		// 如果global存在,展示,不存在,创建
		ActivityGlobal global = this.activityGlobalService.queryGlobalByNick(seller.getNick());
		// 这里判断时间,当前时间<开始时间,当前时间>结束时间 修改
		int rightCode = ActivityUtility.getRightCode(global.getBeginTime(), global.getEndTime());
		request.setAttribute("rightCode", rightCode);
		request.setAttribute("global", global);
		return "activity/act_global";
	}

	/**
	 * 修改全局属性
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/globalSuspend")
	public String suspendGlobalStatus(HttpServletRequest request,
			HttpServletResponse response)
	{
		// 从session中获取User
		SiteSeller seller = ActivityUtility.getSellerFromSession(request.getSession());
		// 查询活动信息
		ActivityGlobal global = this.activityGlobalService.queryGlobalByNick(seller.getNick());
		// 暂停全局活动
		this.activityGlobalService.modifyActivityStatus(global.getId(), seller.getNick(),
				Constant.ACTIVITY_STATUS_SUSPEND);

		global.setStatus(Constant.ACTIVITY_STATUS_SUSPEND);
		// 这里判断时间,当前时间<开始时间,当前时间>结束时间 修改
		int rightCode = ActivityUtility.getRightCode(global.getBeginTime(), global.getEndTime());
		request.setAttribute("rightCode", rightCode);
		request.setAttribute("global", global);
		return "activity/act_global";
	}

	/**
	 * 修改全局属性
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/globalResume")
	public String resumeGlobalStatus(HttpServletRequest request,
			HttpServletResponse response)
	{
		// 从session中获取User
		SiteSeller seller = ActivityUtility.getSellerFromSession(request.getSession());
		// 查询活动信息
		ActivityGlobal global = this.activityGlobalService.queryGlobalByNick(seller.getNick());
		// 恢复全局活动
		this.activityGlobalService.modifyActivityStatus(global.getId(), seller.getNick(),
				Constant.ACTIVITY_STATUS_RUNNING);

		global.setStatus(Constant.ACTIVITY_STATUS_RUNNING);
		// 这里判断时间,当前时间<开始时间,当前时间>结束时间 修改
		int rightCode = ActivityUtility.getRightCode(global.getBeginTime(), global.getEndTime());
		request.setAttribute("rightCode", rightCode);
		request.setAttribute("global", global);
		return "activity/act_global";
	}

	/**
	 * 修改个人全局属性
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/globalmodify")
	public String modifyGlobal(@RequestParam Map<String, String> paramters,
			HttpServletRequest request, HttpServletResponse response)
	{
		// 从session中获取User
		SiteSeller seller = ActivityUtility.getSellerFromSession(request.getSession());
		// 从paramters中获取global
		ActivityGlobal global = ActivityUtility.getGlobalFromParamters(paramters, 102);
		global.setNick(seller.getNick());
		global.setIdSeller(seller.getId());

		// 修改
		this.activityGlobalService.modifyActivityGlobal(global);
		request.setAttribute("global", global);
		int rightCode = ActivityUtility.getRightCode(global.getBeginTime(), global.getEndTime());
		request.setAttribute("rightCode", rightCode);
		return "activity/act_global";
	}

	/**
	 * 察看宝贝页面
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/list")
	public String showActivities(HttpServletRequest request, HttpServletResponse response)
			throws IOException
	{
		// 从session中获取User
		SiteSeller seller = ActivityUtility.getSellerFromSession(request.getSession());
		// 查询当前所有的宝贝-->查看当前自己的所有宝贝
		List<ActivityBean> list = this.activityService.queryActivityInfoByNick(seller.getNick());
		request.setAttribute("actList", list);

		// 根据模板id查询模板信息
		List<ActivitySettingBean> actSettingList = this.activitySettingService
				.queryAllActSetting(seller.getNick());
		request.setAttribute("actSettingList", actSettingList);
		return "activity/act_list";
	}

	/**
	 * 宝贝列表展示之后查询宝贝的第一个商品图片,没有的话返回
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getURL")
	@ResponseBody
	public String showActivitiesURL(HttpServletRequest request,
			@RequestParam Map<String, String> parameter)
	{
		String ids = parameter.get("ids");
		if (ids == null || "".equals(ids))
		{
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", "404");
			return JSONTranslator.toJSON(map);
		}
		// 查询各个宝贝组中第一个商品的信息
		List<ActivityItemBean> itemList = this.activityItemService.queryActItemByActIds(ids);
		// 根据活动商品id查询淘宝平台的商品信息,sdk中一次查询不能超过20
		int count = itemList.size() / 20;
		Set<SiteItem> itemSet = new HashSet<SiteItem>();
		// 存储宝贝对应url的集合
		Map<String, String> urlMap = new HashMap<String, String>();
		Map<String, String> tmpMap = new HashMap<String, String>();
		for (int i = 0; i <= count; i++)
		{
			int toIndex = (i + 1) * 20 > itemList.size() ? itemList.size() : (i + 1) * 20;
			List<ActivityItemBean> subIdList = itemList.subList(i * 20, toIndex);
			StringBuffer buf = new StringBuffer();
			for (ActivityItemBean subId : subIdList)
			{
				buf.append(subId.getItemId()).append(",");
				urlMap.put(subId.getItemId() + "", subId.getActivityId() + "");
				// 默认为null
				tmpMap.put(String.valueOf(subId.getActivityId()), "");
			}
			if (buf.length() == 0)
			{
				continue;
			}
			String idStr = buf.substring(0, buf.length() - 1);
			
			// 查询淘宝平台
			try
			{
				itemSet.addAll(this.taobaoService.findItemById(idStr));
			}
			catch (BaseException e)
			{
				e.printStackTrace();
			}
		}
		// 获取宝贝对应的url
		for (SiteItem sItem : itemSet)
		{
			String tmpItemId = String.valueOf(sItem.getCode());
			String tmpActId = urlMap.get(tmpItemId);
			String tmpUrl = sItem.getPicUrl();
			tmpMap.put(tmpActId, tmpUrl);
		}
		return JSONTranslator.toJSON(tmpMap, "utf-8", "utf-8");
	}

	/**
	 * 根据分类的模板察看宝贝
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/showByModel_{modelId}")
	public String showActivityByModel(@PathVariable String modelId, HttpServletRequest request)
	{
		long id = Long.parseLong(modelId);
		// 根据模板察看宝贝
		List<ActivityBean> list = this.activityService.queryActivityByModel(id);
		request.setAttribute("actList", list);

		// 根据模板id查看模板信息
		SiteSeller seller = ActivityUtility.getSellerFromSession(request.getSession());
		List<ActivitySettingBean> actSettingList = this.activitySettingService
				.queryAllActSetting(seller.getNick());
		request.setAttribute("actSettingList", actSettingList);
		return "activity/act_list";
	}

	/**
	 * create activity 创建活动页面
	 * 
	 * @return page
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/create")
	public String showCreateActivity(HttpServletRequest request)
	{
		// 查询活动模板
		SiteSeller seller = ActivityUtility.getSellerFromSession(request.getSession());
		List<ActivitySettingBean> list = activitySettingService
				.queryAllActSetting(seller.getNick());
		request.setAttribute("actSettingList", list);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String nowTime = sdf.format(new Date());
		request.setAttribute("nowTime", nowTime);
		return "activity/act_create";
	}

	/**
	 * 添加活动记录
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/add")
	@ResponseBody
	public String addActivity(@RequestParam Map<String, String> paramters,
			HttpServletRequest request, HttpServletResponse response)
	{
		// 从session中获取User,global
		SiteSeller seller = ActivityUtility.getSellerFromSession(request.getSession());
		ActivityGlobal global = ActivityUtility.getGlobalFromSession(request.getSession());
		if (null == global)
		{
			global = this.activityGlobalService.queryGlobalByNick(seller.getNick());
			request.getSession().setAttribute("global", global);
		}
		
		//查看是否已存在活动
		List<ActivityBean> actionList = activityService.queryActivityInfoByNick(seller.getNick());
		
		if(!actionList.isEmpty())
		{
			// 已经存在活动
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", "-201");
			return JSONTranslator.toJSON(map);
		}

		// 获取界面上商品的编号
		String jsonString = paramters.get("itemData");
		ArrayList<Long> idList = JSONTranslator.toCollection(jsonString, ArrayList.class,
				Long.class);

		// 从参数中创建活动实例
		ActivityBean bean = ActivityUtility.getActBeanFromParamters(paramters, idList.size(),
				seller);
		if (bean == null)
		{
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", "202");
			return JSONTranslator.toJSON(map);
		}

		// 向淘宝数据库中添加折扣信息
		try
		{
			bean.setTagId(this.taobaoService.addPromotionFromAction(this.activitySettingService, seller, bean, idList));
		}
		catch (BaseException e)
		{
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", "202");
			return JSONTranslator.toJSON(map);
		}
		// 需要记录卖家信息,对应外健//id_seller=t_sitn_seller.id
		// bean.setSellerId(seller.getId());
		bean.setGlobalId(global.getId());
		// 数据库中增加活动记录,执行之后//此时的bean中的id为数据库中自增的置
		this.activityService.addActivityBean(bean);

		// 添加活动商品记录
		List<ActivityItemBean> itemList = new ArrayList<ActivityItemBean>();
		for (Long itemId : idList)
		{
			ActivityItemBean item = new ActivityItemBean();
			item.setItemId(itemId.longValue());
			// 此时的bean中的id为数据库中自增的置
			item.setActivityId(bean.getAid());
			itemList.add(item);
		}
		// 将活动记录批量添加到数据库中
		this.activityItemService.addActivityItemBatch(itemList);

		// 增加活动完成
		Map<String, String> map = new HashMap<String, String>();
		map.put("code", "201");
		return JSONTranslator.toJSON(map);
	}

	/**
	 * query items
	 * 
	 * @return page
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/query")
	@ResponseBody
	public String requestItem(HttpServletRequest request,
			@RequestParam Map<String, String> parameter)
	{
		// {sord=desc, page=2, nd=1307002296967, sidx=id, _search=false,
		// rows=10}
		long pageNo = GridPage.DEFAULT_PAGE_NO;
		long pageSize = GridPage.DEFAULT_PAGE_SIZE;
		if (null != parameter && !parameter.isEmpty())
		{
			pageNo = Long.parseLong(parameter.get("page"));
			pageSize = Long.parseLong(parameter.get("rows"));
			//pageSize = 3L;
		}
		String type = parameter.get("type");

		HttpSession session = request.getSession();
		Object obj = session.getAttribute("seller");
		SiteSeller seller = null;
		List<Item> itemList = new ArrayList<Item>();
		String json = "";
		if (null != obj)
		{
			seller = (SiteSeller) obj;
			try
			{
				TaobaoItemResult result = this.taobaoService.getItemByParameter(seller.getTopSession(),
						"", pageNo, pageSize);
				itemList = result.getItemList();
				if (itemList == null || itemList.size() == 0)
				{
					// 没有宝贝
					return json;
				}
				//获取全部商品数量
				long totalNum = result.getTotal();
				long otherNum = 0;

				//这里将已经加入活动的宝贝删除修改\创建
				if ("edit".equals(type) || "create".equals(type))
				{
					long actId = 0;
					String tmpAct = parameter.get("actId");
					if (null != tmpAct && !"".equals(tmpAct))
					{
						actId = Long.parseLong(tmpAct);
					}
					//1查询当前用户创建的活动并对应的商品id
					List<Long> usedIds = this.activityItemService.queryActItemIdsByNick(seller.getNick(), actId);
					//从淘宝平台的查询数据中删除
					Iterator<Item> iter = itemList.iterator();
					while (iter.hasNext())
					{
						Item item = iter.next();
						if (usedIds.contains(item.getNumIid()))
						{
							iter.remove();
						}
					}
					//重设最大数据值
					result.setTotal(totalNum - usedIds.size());
					//参与其它组商品数
					otherNum = usedIds.size();
				}
				
				List xpddItemList = taobaoService.changeSiteItem(itemList);
				GridPage gridPage = new GridPage();
				gridPage.setPage(pageNo);
				gridPage.setRecords(result.getTotal());
				gridPage.setTotal(result.getTotal() % pageSize == 0 ? result.getTotal() / pageSize
						: result.getTotal() / pageSize + 1);
				gridPage.setRows(xpddItemList);
				gridPage.setTotalNum(totalNum);
				gridPage.setOtherNum(otherNum);
				json = JSONTranslator.toJSON(gridPage);
				// json = json.replaceAll("\"id\"", "id");
			}
			catch (BaseException e)
			{
				logger.error(e.getMessage(), e);
			}

			return json;
		}

		return "";
	}

	/**
	 * activity detail 查询活动的详细信息
	 */
	@RequestMapping(value = "/act_{id}", method = RequestMethod.GET)
	public String getActivityById(@PathVariable String id, HttpServletRequest request)
	{
		long aid = Long.parseLong(id);
		// 活动模板
		SiteSeller seller = ActivityUtility.getSellerFromSession(request.getSession());
		// 根据活动id查询活动信息
		ActivityBean actBean = this.activityService.queryActivityBeanById(aid);
		// 判断是否用户创建的活动
		if (!actBean.getNick().equals(seller.getNick()))
		{
			request.setAttribute("error", "非法的请求");
			return "error";
		}
		request.setAttribute("actBean", actBean);

		// 查询活动成交记录
		List<ActivityRecordBean> actRecordList = new ArrayList<ActivityRecordBean>();
		actRecordList = this.activityRecordService.queryActRecordByActId(aid, 8);
		request.setAttribute("actRecordList", actRecordList);

		// 获取活动状态描述
		String activityDesc = ActivityUtility.getActDesc(actBean);
		request.setAttribute("activityDesc", activityDesc);

		// 根据活动的模板id查询模板信息
		ActivitySettingBean actSetting = this.activitySettingService.queryActSettingById(actBean
				.getModleId());
		request.setAttribute("actSettingBean", actSetting);
		return "activity/act_detail";
	}

	/**
	 * 活动详细页面察看更多活动
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/getActivityByIdMore")
	public String getActivityByIdMore(HttpServletRequest request,
			@RequestParam Map<String, String> parameter)
	{
		String tmpId = parameter.get("id");
		long aid = Long.parseLong(tmpId);
		// 活动模板
		SiteSeller seller = ActivityUtility.getSellerFromSession(request.getSession());
		// 这里查询4个id!=aid的活动
		List<ActivityBean> list = this.activityService.queryActivityLimit(aid, seller.getNick(), 4);
		request.setAttribute("moreList", list);
		return "activity/act_detail_more";
	}

	/**
	 * 编辑活动
	 */
	@RequestMapping(value = "/edit_{id}", method = RequestMethod.GET)
	public String editActivityById(@PathVariable String id, HttpServletRequest request)
	{
		long aid = Long.parseLong(id);
		// 根据活动id查询活动信息
		ActivityBean actBean = this.activityService.queryActivityBeanById(aid);
		// 活动模板
		SiteSeller seller = ActivityUtility.getSellerFromSession(request.getSession());
		// 判断是否用户创建的活动
		if (!actBean.getNick().equals(seller.getNick()))
		{
			request.setAttribute("error", "非法的请求");
			return "error";
		}
		request.setAttribute("actBean", actBean);
		//策略模板
		List<ActivitySettingBean> list = activitySettingService.queryAllActSetting(seller.getNick());
		request.setAttribute("actSettingList", list);

		// 查询活动下的商品Id信息
		List<Long> itemIdList = this.activityItemService.queryActItemIdsByActId(actBean.getAid());
		request.setAttribute("jsonItemId", JSONTranslator.toJSON(itemIdList));
		return "activity/act_edit";
	}

	/**
	 * 修改活动
	 */
	@RequestMapping(value = "/modifyAct", method = RequestMethod.POST)
	public String modifyActivityById(@RequestParam Map<String, String> paramters,
			HttpServletRequest request)
	{
		// 获取商家登录信息
		SiteSeller seller = (SiteSeller) request.getSession().getAttribute("seller");
		long aid = Long.parseLong(paramters.get("actId"));
		// 根据活动id查询活动信息
		ActivityBean actBean = this.activityService.queryActivityBeanById(aid);
		// 获取界面上商品的编号
		String jsonString = paramters.get("itemData");
		ArrayList<Long> idList = JSONTranslator.toCollection(jsonString, ArrayList.class,
				Long.class);
		actBean.setXpddItemSize(idList.size());
		// 从参数中修改活动
		ActivityUtility.modifyActFromParamters(paramters, actBean);

		// 修改数据库活动
		this.activityService.modifyActivityBean(actBean);

		// 查询活动对应的商品id集合,判断是否需要修改
		List<Long> itemIdList = this.activityItemService.queryActItemIdsByActId(actBean.getAid());
		// 获取新增活动商品记录
		List<ActivityItemBean> addItemList = ActivityUtility.getNewActItemList(itemIdList, idList,
				aid);
		// 获取删除商品记录
		List<Long> delItemIdList = ActivityUtility.getDelActItemIdList(itemIdList, idList);
		
		// 编辑定向优惠信息
		if ((null != addItemList && !addItemList.isEmpty()) || (null != delItemIdList && !delItemIdList.isEmpty()))
		{
			try
			{
				// 删除该活动的定向优惠
				this.taobaoService.removePromotionByAction(this.activityService, seller, aid);
				
				// 重置标签人群
				this.accountService.resetTagUser(seller, this.taobaoService);
				
				// 添加该活动的定向优惠
				this.taobaoService.addPromotionFromAction(activitySettingService, seller, actBean,
						idList);
			}
			catch (BaseException e)
			{
				request.setAttribute("error", "编辑活动失败");
				return "error";
			}
		}
		
		// 如果存在新增商品入库
		if (addItemList.size() > 0)
		{
			this.activityItemService.addActivityItemBatch(addItemList);
		}
		// 如果存在删除商品id删除数据库记录
		if (delItemIdList.size() > 0)
		{
			this.activityItemService.delActivityItemByIdBatch(aid, delItemIdList);
		}
		
		// 转到活动详细信息察看页面
		request.setAttribute("actBean", actBean);
		// 获取活动状态
		List<ActivityRecordBean> actRecordList = new ArrayList<ActivityRecordBean>();
		// 查询活动成交记录
		actRecordList = this.activityRecordService.queryActRecordByActId(aid, 8);
		request.setAttribute("actRecordList", actRecordList);
		// 获取活动状态描述
		String activityDesc = ActivityUtility.getActDesc(actBean);
		request.setAttribute("activityDesc", activityDesc);
		// 根据活动的模板id查询模板信息
		ActivitySettingBean actSetting = this.activitySettingService.queryActSettingById(actBean
				.getModleId());
		request.setAttribute("actSettingBean", actSetting);
		return "activity/act_detail";
	}

	/**
	 * 删除活动
	 */
	@RequestMapping(value = "/del_{id}")
	public String delActivityById(@PathVariable String id, HttpServletRequest request)
	{
		SiteSeller seller = (SiteSeller) request.getSession().getAttribute("seller");
		// 活动id
		long aid = Long.parseLong(id);
		// 根据活动id查询活动信息
		ActivityBean actBean = this.activityService.queryActivityBeanById(aid);
		// 判断是否用户创建的活动
		if (!actBean.getNick().equals(seller.getNick()))
		{
			request.setAttribute("error", "非法的请求");
			return "error";
		}

		// 1、删除人群标签用户
		try
		{
			this.taobaoService.removePromotionByAction(activityService, seller, aid);
		}
		catch (BaseException e)
		{
			e.printStackTrace();
		}

		// 2、删除成交记录
		this.activityRecordService.delActRecordByActId(aid);
		// 3、删除活动商品
		this.activityItemService.delActivityItemBeanByActId(aid);
		// 4、删除活动记录
		this.activityService.delActivityBeanById(aid);
		// 5转到宝贝列表界面
		List<ActivityBean> list = this.activityService.queryActivityInfoByNick(seller.getNick());
		request.setAttribute("actList", list);
		// 根据模板id查询模板信息
		List<ActivitySettingBean> actSettingList = this.activitySettingService
				.queryAllActSetting(seller.getNick());
		request.setAttribute("actSettingList", actSettingList);
		return "activity/act_list";
	}

	/**
	 * 根据活动id查询活动的成交记录
	 */
	@RequestMapping(value = "/record_{id}")
	public String showRecordsByActId(@PathVariable String id, HttpServletRequest request)
	{
		// 活动id
		long aid = Long.parseLong(id);
		SiteSeller seller = (SiteSeller) request.getSession().getAttribute("seller");
		// 根据活动id查询活动信息
		ActivityBean actBean = this.activityService.queryActivityBeanById(aid);
		// 判断是否用户创建的活动
		if (!actBean.getNick().equals(seller.getNick()))
		{
			request.setAttribute("error", "非法的请求");
			return "error";
		}
		// 查询活动的成交记录
		List<ActivityRecordBean> recordList = this.activityRecordService.queryActRecordByActId(aid, 8);
		request.setAttribute("actRecordList", recordList);
		request.setAttribute("aid", aid);
		return "activity/act_records";
	}

	/**
	 * 根据活动id查询活动的成交记录
	 */
	@ResponseBody
	@RequestMapping(value = "/syncdeal", method = RequestMethod.GET)
	public String syncDeallReacord(HttpServletRequest request)
	{
		// 返回对象
		JSONResponse jsonResponse = new JSONResponse();

		try
		{
			// 获取当前卖家
			SiteSeller seller = (SiteSeller) request.getSession().getAttribute("seller");
			
			// 查询是否有未同步的交易记录
			List<ActivityRecordBean> dealList = this.activityRecordService
					.findUnsyncDealRecordBySeller(seller);

			// 如果有 查询 则根据价格 同步 即添加买家到相应标签人群
			if (null != dealList && !dealList.isEmpty())
			{
				// 获取商品信息id - price map
				// Map<Long, Double> itemList =
				// this.activityItemService.findItemBySellerAsMap(seller);
				for (ActivityRecordBean deal : dealList)
				{
					// 获取折扣信息
					String result = this.taobaoService.findPromotionByItemId(
							seller.getTopSession(), deal.getItemId());

					// 匹配折扣信息 找到promotionid
					LinkedHashMap map = JSONTranslator.toBean(result, LinkedHashMap.class);
					ArrayList<LinkedHashMap> promotionList = (ArrayList) ((LinkedHashMap) ((LinkedHashMap) map
							.get("marketing_promotions_get_response")).get("promotions"))
							.get("promotion");
					for (LinkedHashMap tempMap : promotionList)
					{
						String discountValue = tempMap.get("discount_value").toString();
						String itemDetailUrl = tempMap.get("item_detail_url").toString();
						String tagId = tempMap.get("tag_id").toString();
						if (Double.parseDouble(discountValue) == deal.getDiscount())
						{
							// 添加标签用户
							this.taobaoService.addTagBuyer(seller.getTopSession(),
									Long.parseLong(tagId), deal.getBuyerNick());
							this.activityRecordService.saveSyncStatus(deal);
							break;
						}
					}
				}

			}

			jsonResponse.setCode("0");
			jsonResponse.setMessage("同步完成");
		}
		catch (Exception e)
		{
			jsonResponse.setCode("-1");
			jsonResponse.setMessage("同步失败, 请联系管理员");
		}
		// 查询活动的成交记录
		// List<ActivityRecordBean> recordList =
		// this.activityRecordService.queryActRecordByActId(aid);
		// request.setAttribute("actRecordList", recordList);
		// request.setAttribute("aid", aid);
		return jsonResponse.toString();
	}
}
